import http from "http";
import config from "./config";
import querystring from "querystring";
import fs from 'fs';
// const { URL, URLSearchParams } = require('url');
import URL from 'url';
import path from 'path';
import axios from 'axios';

const baseUrl = URL.parse(config('baseURL',true));


export default function api(app) {
    app.use(async(ctx, next) => {
    	let instance = axios.create({
		  baseURL: config('baseURL',true),
		  timeout: 10000,
		});
    	ctx.post = async (url,params={}) => {
    		let headers = {
		      'Content-Type': 'application/json',
		    }
			if(ctx.ticket){
			 	headers["cookie"]=ctx.ticket;
			}
    		let result = {};
    		try{
    			result = await instance.post(url,JSON.stringify(params),{headers})
    		}catch(e){
    			result = e.response;
    		}
    		let cookie = result.headers['set-cookie'];
    		if(cookie){
    			ctx.sess({ticket:cookie[0].split(';')[0] })
    		}
    		return result.data;
    	}

    	ctx.get = async (url,params={}) => {
    		let {...other} = params;
    		let headers = {
		      'Content-Type': 'application/json',
		    }
			if(ctx.ticket){
			 	headers["cookie"]=ctx.ticket;
			}
    		let result = {};
    		try{
    			let strParams = querystring.stringify(params);
    			let urlObj = URL.parse(url);
				url = urlObj.pathname + (urlObj.search?urlObj.search + '&'+strParams:'?'+strParams) + (urlObj.hash?urlObj.hash:''); 
    			result = await instance.get(url,{headers})
    		}catch(e){
    			result = e.response
    		}
    		return result.data;
    	} 

    	ctx.upload = async (url,files) => {
    		return await upload(ctx,url,files);
    	}

        await next();
    });
}

function upload(ctx,url,params){
	return new Promise((resolve,reject) => {
		let options = { 
			host: baseUrl.host, 
			port: baseUrl.port||"80" , 
			method: "POST", 
			path: url,
			headers:{'Cookie':ctx.ticket}
		}
		let req = http.request(options, function(res){
		 		//res.setEncoding("utf8");
				res.on("data", function(chunk){
					resolve(JSON.parse(chunk));
				  	console.log("BODY:" + chunk);
				})
			})
		req.on('error', function(e){
			resolve({cd:0,msg:'上传发生错误'})
		 // console.log('problem with request:' + e.message);
		 // console.log(e);
		})
		postFile(params, req);
	})
}

function postFile(fileKeyValue, req) {
	let boundaryKey = Math.random().toString(16);
	let enddata = '\r\n----' + boundaryKey + '--';
	let files = new Array();
	for (var i = 0; i < fileKeyValue.length; i++) {
	   let content =`\r\n----${boundaryKey}\r\nContent-Type: application/octet-stream\r\nContent-Disposition: form-data; name=${fileKeyValue[i].urlKey}; filename=${path.basename(fileKeyValue[i].urlValue)}\r\nContent-Transfer-Encoding: binary\r\n\r\n`;
	   let contentBinary = new Buffer(content, 'utf-8');//当编码为ascii时，中文会乱码。
	   files.push({contentBinary: contentBinary, filePath: fileKeyValue[i].urlValue});
	}
	let contentLength = 0;
	for (let i = 0; i < files.length; i++) {
	   let stat = fs.statSync(files[i].filePath);
	   contentLength += files[i].contentBinary.length;
	   contentLength += stat.size;
	}
  	req.setHeader('Content-Type', 'multipart/form-data; boundary=--' + boundaryKey);
	req.setHeader('Content-Length', contentLength + Buffer.byteLength(enddata));
	  // 将参数发出
	let fileindex = 0;
	function doOneFile(){
	    req.write(files[fileindex].contentBinary);
	    var fileStream = fs.createReadStream(files[fileindex].filePath, {bufferSize : 4 * 1024});
	    fileStream.pipe(req, {end: false});
	    fileStream.on('end', function() {
	    	fileindex++;
	     	if(fileindex == files.length){
	      		req.end(enddata);
	     	} else {
	      		doOneFile();
	     	}
	    });
	};
  	if(fileindex == files.length){
	    req.end(enddata);
  	} else {
	    doOneFile();
	}      
}

